package com.zhiyizhen.handheld.component.execute;

import static com.zhiyizhen.handheld.common.AppUtil.getSystemService;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CalendarView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentTransaction;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.DateUtil;
import com.zhiyizhen.handheld.common.LogUtil;
import com.zhiyizhen.handheld.common.RecyclerViewUtil;
import com.zhiyizhen.handheld.common.ResourcesUtil;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.ScreenUtil;
import com.zhiyizhen.handheld.common.constant.AppConstant;
import com.zhiyizhen.handheld.common.event.ChangeExecuteStatusEvent;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.component.execute.adapter.ExecuteAdapter;
import com.zhiyizhen.handheld.component.execute.api.IExecuteService;
import com.zhiyizhen.handheld.component.execute.bean.ExecuteUserBean;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.databinding.FragmentLiliaoDrawerBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 理疗
 */
public class LiliaoFragment extends BaseFragment {
    private FragmentLiliaoDrawerBinding binding;
    private ExecuteAdapter executeAdapter;
    private LoginBean loginBean;
    private String visitDate;
    private int mPage = 1;

    private LiliaoDetailFragment detailFragment;

    private DrawerLayout drawerLayout;
    private ExecuteRecordFragment executeRecordFragment;
    private ChargeRecordFragment chargeRecordFragment;
    private FragmentTransaction fragmentTransaction;
    private final static int executeRecordFragmentIndex = 1;
    private final static int chargeRecordFragmentIndex = 2;
    private int currentIndex = 0;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentLiliaoDrawerBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 初始化DrawerLayout
        drawerLayout = view.findViewById(R.id.drawerLayout);
        // 等视图加载完成后获取父容器尺寸
        drawerLayout.post(() -> {
            if (drawerLayout.getParent() instanceof View) {
                View parentView = (View) drawerLayout.getParent();
                // 等待父容器完成测量
                parentView.post(() -> {
                    // 设置固定尺寸
                    ViewGroup.LayoutParams params = drawerLayout.getLayoutParams();
                    params.width = ScreenUtil.screenWidth() - ScreenUtil.dp2px(80);
                    params.height = ScreenUtil.screenHeight();
                    drawerLayout.setLayoutParams(params);
                });
            }
        });
        loginBean = DataCache.getLoginBean();
        visitDate = DateUtil.getCurrentDate();
        initView();
        initTabLayout();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            loadData(1);
        }
    }

    private void initTabLayout() {
        executeRecordFragment = new ExecuteRecordFragment(ExecuteRecordFragment.LILIAO);
        chargeRecordFragment = new ChargeRecordFragment(ChargeRecordFragment.LILIAO);
        fragmentTransaction = getChildFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, executeRecordFragment);
        fragmentTransaction.add(R.id.fragment_container, chargeRecordFragment);
        hideFragments(fragmentTransaction, executeRecordFragmentIndex);
        showExecuteRecordFragment(fragmentTransaction);

        binding.executeRecordTv.setOnClickListener(view -> {
            if (currentIndex == executeRecordFragmentIndex) {
                return;
            }
            fragmentTransaction = getChildFragmentManager().beginTransaction();
            hideFragments(fragmentTransaction, executeRecordFragmentIndex);
            showExecuteRecordFragment(fragmentTransaction);

        });
    }

    private void initView() {
        drawerLayout = binding.drawerLayout;
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        detailFragment = new LiliaoDetailFragment();
        getChildFragmentManager().beginTransaction()
                .setReorderingAllowed(true)
                .add(R.id.executeUserFragment, detailFragment, null)
                .commit();

        CalendarView calendarView = binding.container.calendarView;
        Calendar today = Calendar.getInstance();
        today.setTimeInMillis(System.currentTimeMillis());
        today.add(Calendar.DAY_OF_MONTH, 0);
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);
//        calendarView.setMinDate(today.getTimeInMillis());
        calendarView.setVisibility(View.GONE);

        binding.container.chooseDateBtn.setOnClickListener(v -> {
            if (calendarView.getVisibility() == View.GONE) {
                calendarView.setVisibility(View.VISIBLE);
            } else {
                calendarView.setVisibility(View.GONE);
            }
        });
        binding.openDrawerLayoutImg.setOnClickListener(v -> drawerLayout.openDrawer(binding.testLayout));
        binding.closeDrawerBtn.setOnClickListener(v -> drawerLayout.closeDrawer(GravityCompat.END, true));
        calendarView.setOnDateChangeListener((view, year, month, dayOfMonth) -> {
            calendarView.setVisibility(View.GONE);
            String day;
            if (dayOfMonth < 10) {
                day = "0" + dayOfMonth;
            } else {
                day = String.valueOf(dayOfMonth);
            }
            String monthString;
            if (month + 1 < 10 ) {
                monthString = "0" + (month + 1);
            } else {
                monthString = String.valueOf(month + 1);
            }
            visitDate = year + "-" + monthString + "-" + day;
            loadData(1);
            String dateString = monthString + "-" + day;
            if (DateUtil.isToday(visitDate)) {
                dateString = "今天";
            }
            binding.container.chooseDateTv.setText(dateString);
        });

        RecyclerViewUtil.configLVRecyclerView(getContext(), binding.container.recyclerView);
        executeAdapter = new ExecuteAdapter(this.getContext());
        executeAdapter.setOnItemClickListener((view, position) -> chooseItem(position, executeAdapter.getItem(position).getOrderId()));
        binding.container.recyclerView.setAdapter(executeAdapter);
        binding.container.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(1);
            }

            @Override
            public void onLoadMore() {
                loadData(mPage + 1);
            }
        });

        binding.container.userNameEdit.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是搜索键触发
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 处理搜索逻辑
                performSearch();

                // 隐藏键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

                return true;
            }
            return false;
        });

    }

    private void performSearch() {
        loadData(1);
    }

    private void hideFragments(FragmentTransaction fragmentTransaction, int selectIndex) {
        if (selectIndex == executeRecordFragmentIndex) {
            fragmentTransaction.hide(chargeRecordFragment);
        } else if (selectIndex == chargeRecordFragmentIndex) {
            fragmentTransaction.hide(executeRecordFragment);
        }
    }

    private void showExecuteRecordFragment(FragmentTransaction fragmentTransaction) {
        currentIndex = executeRecordFragmentIndex;
        fragmentTransaction.show(executeRecordFragment);
        fragmentTransaction.commit();

        binding.executeRecordTv.setTextColor(ResourcesUtil.getColor(R.color.black_e6));
        binding.executeRecordTv.setTypeface(binding.executeRecordTv.getTypeface(), Typeface.BOLD);
    }

    private void chooseItem(int position, String orderId) {
        executeAdapter.setSelectPosition(position);
        detailFragment.setExtraData(DataCache.getEnumsBean(), orderId);

        executeRecordFragment.setData(orderId, DataCache.getEnumsBean().getDicts().getExecTypeBeanList());
        chargeRecordFragment.setData(orderId, DataCache.getEnumsBean().getEnums().getPayStatusEnum());
    }

    private void setEmptyData() {
        detailFragment.setEmptyData();
        executeRecordFragment.setEmptyData();
        chargeRecordFragment.setEmptyData();
    }

    private void loadData(final int page) {
        Map<String, Object> map = new ArrayMap<>();
        String patientName = binding.container.userNameEdit.getText().toString();
        map.put(AppConstant.PAGE_NO, page);
        map.put(AppConstant.PAGE_SIZE, AppConstant.EXECUTE_PER_PAGE);
        map.put(AppConstant.EXEC_CATEGORY, 2);
        if (!TextUtils.isEmpty(patientName)) {
            map.put(AppConstant.PATIENT_NAME, patientName);
        }
        if (!TextUtils.isEmpty(visitDate)) {
            map.put(AppConstant.VISIT_DATE, visitDate);
        }
        ServiceFactory.getService(IExecuteService.class)
                .getExecList(loginBean.getToken(), loginBean.getClinicId(), map)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    boolean hasMore = true;
                    boolean success = false;

                    @Override
                    protected void onSuccess(ResponseData<List<ExecuteUserBean>> responseData) {
                        success = true;
                        mPage = page;

                        List<ExecuteUserBean> list = responseData.getData();
                        if (mPage == 1) {
                            executeAdapter.setData(list);
                            if (list != null && !list.isEmpty()) {
                                chooseItem(0, executeAdapter.getItem(0).getOrderId());
                            } else {
                                setEmptyData();
                            }
                        } else {
                            executeAdapter.addAll(list);
                        }
                        hasMore = (list != null && list.size() == AppConstant.EXECUTE_PER_PAGE);
                    }

                    @Override
                    protected void onFinally() {
                        RecyclerViewUtil.loadComplete(binding.container.recyclerView, mPage, success, !hasMore, executeAdapter.getItemCount() <= 0);
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateExecuteStatusCount(ChangeExecuteStatusEvent event) {
        LogUtil.d("-----updateExecuteStatusCount-----");
        String orderId = event.getOrderId();
        for (int i = 0; i < executeAdapter.getItemCount(); i++) {
            ExecuteUserBean bean = executeAdapter.getItem(i);
            if (bean.getOrderId().equals(orderId)) {
                bean.setExecStatus("3");
                break;
            }
        }
        executeAdapter.notifyDataSetChanged();
    }

}
